<?php

namespace app\admin\controller\classes;

use app\common\controller\Backend;
use think\Db;

/**
 * 教学点班级管理
 *
 * @icon fa fa-building
 */
class OcationClass extends Backend
{
    /**
     * OcationClass模型对象
     */
    protected $model = null;
    protected $noNeedRight = ["index", "detail"];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('OcationClass');
        $this->modelValidate = true;
    }
    
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            // 构建总数查询
            $total = $this->model->alias('oc')
                ->join('fa_ocation o', 'o.id = oc.ocation_id', 'LEFT')
                ->where("oc.status", "=", 1);
            
            if (isset($_REQUEST['search']) && $_REQUEST['search'] != "") {
                $total = $total->where("oc.name|o.name", "like", "%".$_REQUEST['search']."%");
            }
            
            $total = $total->count();
            $this->assign('total', $total);
            
            // 构建列表查询
            $list = $this->model->alias('oc')
                ->join('fa_ocation o', 'o.id = oc.ocation_id', 'LEFT')
                ->field('oc.*, o.name as ocation_name')
                ->where("oc.status", "=", 1);
            
            if (isset($_REQUEST['search']) && $_REQUEST['search'] != "") {
                $list = $list->where("oc.name|o.name", "like", "%".$_REQUEST['search']."%");
            }
            
            // 处理排序
            if ($sort === 'sequence_number') {
                $list = $list->order("oc.sequence_number {$order}")
                    ->limit($offset, $limit)
                    ->select();
            } else {
                $list = $list->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }
            
            // 将查询结果转换为数组
            $list = is_array($list) ? $list : ($list ? $list->toArray() : []);
            
            // 处理数据
            foreach ($list as &$item) {
                // 获取课程数量
                $item['course_count'] = Db::name('ocation_class_course')
                    ->where('ocation_class_id', $item['id'])
                    ->where('status', 1)
                    ->count();
                
                // 格式化序号
                $item['formatted_sequence'] = \app\admin\model\OcationClass::getFormattedSequence($item['sequence_number']);
                
                // 处理封面图片
                if (!empty($item['cover'])) {
                    $item['cover'] = createImg($_SERVER["DOCUMENT_ROOT"]."/".$item["cover"], "220", "220");
                }
            }
            
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        
        return $this->view->fetch();
    }
    
    /**
     * 查看班级详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取关联的课程
        $courses = Db::name('ocation_class_course occ')
            ->join('eb_classes c', 'c.id = occ.class_id', 'LEFT')
            ->field('c.*, occ.id as relation_id')
            ->where('occ.ocation_class_id', $ids)
            ->where('occ.status', 1)
            ->where('c.status', 1)
            ->select();
        
        $this->view->assign('row', $row);
        $this->view->assign('courses', $courses);
        
        return $this->view->fetch();
    }
    
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    // 获取下一个序号
                    $params['sequence_number'] = \app\admin\model\OcationClass::getNextSequence();
                    
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        return $this->view->fetch();
    }
    
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }
    
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    // 删除关联的课程
                    Db::name('ocation_class_course')
                        ->where('ocation_class_id', $v->id)
                        ->delete();
                    
                    $count += $v->delete();
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    
    /**
     * 添加课程
     */
    public function addCourse($ids = null)
    {
        $ocationClass = $this->model->get($ids);
        if (!$ocationClass) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $classIds = $this->request->post("class_ids/a");
            if ($classIds) {
                try {
                    $count = 0;
                    foreach ($classIds as $classId) {
                        // 检查是否已经关联
                        $exists = Db::name('ocation_class_course')
                            ->where('ocation_class_id', $ids)
                            ->where('class_id', $classId)
                            ->find();
                        
                        if (!$exists) {
                            $data = [
                                'ocation_class_id' => $ids,
                                'class_id' => $classId,
                                'status' => 1,
                                'create_time' => date('Y-m-d H:i:s'),
                                'update_time' => date('Y-m-d H:i:s')
                            ];
                            
                            Db::name('ocation_class_course')->insert($data);
                            $count++;
                        }
                    }
                    
                    if ($count) {
                        $this->success("成功添加 {$count} 个课程");
                    } else {
                        $this->error("没有添加任何课程");
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', 'class_ids'));
        }
        
        // 获取可用的社区班级（课程）
        $classes = Db::name('eb_classes')
            ->where('classes_type', 2) // 社区班级
            ->where('status', 1)
            ->where('ocation_id', $ocationClass['ocation_id']) // 同一个教学点
            ->select();
        
        // 获取已关联的课程ID
        $existingClassIds = Db::name('ocation_class_course')
            ->where('ocation_class_id', $ids)
            ->column('class_id');
        
        // 过滤掉已关联的课程
        $availableClasses = [];
        foreach ($classes as $class) {
            if (!in_array($class['id'], $existingClassIds)) {
                $availableClasses[] = $class;
            }
        }
        
        $this->view->assign('ocationClass', $ocationClass);
        $this->view->assign('classes', $availableClasses);
        
        return $this->view->fetch();
    }
    
    /**
     * 删除课程
     */
    public function delCourse($ids = null)
    {
        if ($ids) {
            try {
                $relation = Db::name('ocation_class_course')->where('id', $ids)->find();
                if (!$relation) {
                    $this->error("关联记录不存在");
                }
                
                Db::name('ocation_class_course')->where('id', $ids)->delete();
                $this->success();
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}